/**
 * Copyright @2019 Josin All Rights Reserved.
 * Author: Josin
 * Email : xeapplee@gmail.com
 */

#include <mb_socket.h>
#include <fc_string.h>

/**
 * @brief NOTICE
 * Function to Read data from socket and return the read number of
 * bytes
 */
ssize_t mb_socket_read(int fd, void *ptr, size_t plen)
{
    ssize_t      res;
    if ( fd <= 0 ) return FALSE;
    
read_again:
    res = read(fd, ptr, plen);
    
    if ( res == -1 )
    {
        if ( errno == EAGAIN || errno == EINTR )
        {
            goto read_again;
        }
        return FALSE;
    }
    
    return res;
}

/**
 * @brief NOTICE
 * Read number of the string data, and return then size of the data
 * read from the socket
 */
ssize_t mb_socket_read_str_len(int fd, char **ptr, size_t plen)
{
    char *buf = realloc(*ptr, sizeof(char) * plen );
    if ( buf != NULL ) {
        *ptr = buf;
        return mb_socket_read(fd, buf, plen);
    }
    return FALSE;
}


CSTRING *mb_socket_read_stream(int fd)
{
    CSTRING *cstring;
    ssize_t  res_len;
    char     buff[BUFFER_SIZE];
    
    cstring = new_cstring();
    
    while ( TRUE )
    {
        e_memzero( buff, sizeof(char) * BUFFER_SIZE );
        res_len = read( fd, buff, BUFFER_SIZE * sizeof(char) );
        
        if ( res_len == -1 )
        {
            if ( errno == EAGAIN || errno == EINTR )
            {
                continue;
            }
            return cstring;
        }
        
        new_cstring_add_string(cstring, buff, res_len);
        
        if ( res_len < BUFFER_SIZE ) {
            break;
        }
    }
    
    return cstring;
}